package restful

import (
	"gitee.com/go-kade/librarys/ioc"
	"gitee.com/go-kade/librarys/ioc/apps/apidoc"
	"gitee.com/go-kade/librarys/ioc/config/http"
	"gitee.com/go-kade/librarys/ioc/config/log"
	restfulspec "github.com/emicklei/go-restful-openapi/v2"
	"github.com/emicklei/go-restful/v3"
	"github.com/rs/zerolog"
)

func init() {
	ioc.Api().Registry(&SwaggerApiDoc{
		ApiDoc: apidoc.ApiDoc{},
	})
}

type SwaggerApiDoc struct {
	ioc.ObjectImpl
	log *zerolog.Logger

	apidoc.ApiDoc
	// Path string `json:"path" yaml:"path" toml:"path" env:"HTTP_API_DOC_PATH"`
}

func (h *SwaggerApiDoc) Name() string {
	return apidoc.AppName
}

func (h *SwaggerApiDoc) Init() error {
	h.log = log.Sub("api_doc")
	return nil
}

func (i *SwaggerApiDoc) Priority() int {
	return -100
}

func (h *SwaggerApiDoc) Registry(ws *restful.WebService) {
	// 1.该 RESTful Web 服务可以产生 JSON 格式的响应
	ws.Produces(restful.MIME_JSON)
	//2.restfulspec.BuildSwagger() 方法使用这个配置来生成对应的 Swagger 文档
	swagger := restfulspec.BuildSwagger(h.SwaggerDocConfig())

	ws.Route(ws.GET("/").To(func(r *restful.Request, w *restful.Response) {
		w.WriteAsJson(swagger)
	}))

	h.log.Info().Msgf("Get the API Doc using %s", http.Get().ApiObjectAddr(h))
}

// API Doc config
func (h *SwaggerApiDoc) SwaggerDocConfig() restfulspec.Config {
	return restfulspec.Config{
		// 1.是用于获取当前已注册的 Web 服务列表的函数
		WebServices: restful.RegisteredWebServices(),
		// APIPath:     "/swagger.json",
		// APIPath:                       http.Get().ApiObjectPathPrefix(h),
		PostBuildSwaggerObjectHandler: http.Get().SwagerDocs,
		DefinitionNameHandler: func(name string) string {
			if name == "state" || name == "sizeCache" || name == "unknownFields" {
				return ""
			}
			return name
		},
	}
}
